<?php

namespace App\Services\Distribution;

use App\Entity\DistributorPosterEntity;
use App\Entity\UserEntity;
use App\Entity\WechatUserEntity;
use App\Services\File;
use App\Services\Upload;
use App\Services\WechatService;
use App\VO\Product\MetaInfo\ProductInfo;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;

class Poster
{
    //默认类型
    public const FILENAME_POSTER = 'default';

    //商品类型
    public const FILENAME_POSTER_PRODUCT = 'product';

    /**
     * @var UserEntity
     */
    public $user;

    public function __construct(UserEntity $user)
    {
        $this->user = $user;
    }

    /**
     * 生成海报
     * @throws \Exception
     */
    public function make()
    {
        /** @var WechatUserEntity $wechatUser */
        $wechatUser = WechatUserEntity::findByOpenid($this->user->getOpenid());

        $ttf_msyh = resource_path('ttf/msyh.ttf');

        // 源文件
        $filename = resource_path('img/distribution-poster.png');

        $imagecreatefrompng = imagecreatefrompng($filename);
        imagealphablending($imagecreatefrompng, false);
        imagesavealpha($imagecreatefrompng, true);
        $imagecolorallocate_nickname = imagecolorallocate($imagecreatefrompng, 255, 255, 255);

        if ($wechatUser->getHeadimgurl()) {
            $head = File::downloadFromUrl($wechatUser->getHeadimgurl(), $wechatUser->getOpenid() . '.jpg');
            Image::make($head)->resize(96, 96)->save($head);
            $fhead = imagecreatefromjpeg($head);
            imagecopy($imagecreatefrompng, $fhead, 242, 218, 0, 0, imagesx($fhead), imagesy($fhead));
            @unlink($head);
        }

        $poster = storage_path('download/' . $wechatUser->getOpenid() . '.jpg');

        imagejpeg($imagecreatefrompng, $poster);

        //计算昵称位置
        $imgsize = getimagesize($filename);
        $w = $imgsize[0];
        $fsize = 16;
        $mblen = mb_strlen($wechatUser->getNickname());
        $x = ceil(($w - $fsize * $mblen) / 2);
        imagefttext($imagecreatefrompng, 16, 0, $x, 344, $imagecolorallocate_nickname, $ttf_msyh, $wechatUser->getNickname());

        $miniQr = WechatService::createMiniQr('qr-' . $wechatUser->getOpenid() . '.jpg', $this->user->getUserId());
        Image::make($miniQr)->resize(180, 180)->save($miniQr);
        $fminiQr = imagecreatefromjpeg($miniQr);
        imagecopy($imagecreatefrompng, $fminiQr, 200, 446, 0, 0, imagesx($fminiQr), imagesy($fminiQr));
        imagejpeg($imagecreatefrompng, $poster);

        $url = Upload::uploadOss($poster);

        @unlink($miniQr);
        @unlink($poster);

        if (empty($url)) {
            Log::error('上传分销海报失败');
            throw new \Exception('上传分销海报失败');
        }

        $distributorPosterEntity = DistributorPosterEntity::findByUserId($this->user->getUserId());
        if (empty($distributorPosterEntity)) {
            $distributorPosterEntity = DistributorPosterEntity::getNewInstance();
        }
        $distributorPosterEntity->setCreatedAt(Carbon::now()->toDateTimeString());
        $distributorPosterEntity->setOpenid($wechatUser->getOpenid());
        $distributorPosterEntity->setUserId($this->user->getUserId());
        $distributorPosterEntity->setUrl($url);
        $distributorPosterEntity->setType(Constant::POSTER_TYPE_DEFAULT);
        $distributorPosterEntity->save();
        Log::info('分销海报生成成功 url:' . $url);
    }

    /**
     * @param int $city_id
     * @param ProductInfo $productInfo
     * @throws \Exception
     */
    public function makeProduct(int $city_id, ProductInfo $productInfo): void
    {
        /** @var WechatUserEntity $wechatUser */
        $wechatUser = WechatUserEntity::findByOpenid($this->user->getOpenid());

        $ttf_msyh = resource_path('ttf/msyh.ttf');

        // 源文件
        $filename = resource_path('img/distribution-poster-product.png');

        $imagecreatefrompng = imagecreatefrompng($filename);
        imagealphablending($imagecreatefrompng, false);
        imagesavealpha($imagecreatefrompng, true);
        $imagecolorallocate_nickname = imagecolorallocate($imagecreatefrompng, 0, 0, 0);

        //新文件名
        $newfile = $this->getFilename($wechatUser->getOpenid(), self::FILENAME_POSTER_PRODUCT, $productInfo->id);

        //头像
        if ($wechatUser->getHeadimgurl()) {
            $head = File::downloadFromUrl($wechatUser->getHeadimgurl(), $newfile . '.jpg');
            Image::make($head)->resize(80, 80)->save($head);
            $fhead = imagecreatefromjpeg($head);
            imagecopy($imagecreatefrompng, $fhead, 25, 30, 0, 0, 80, 80);
            @unlink($head);
        }

        $poster = storage_path('download/' . $newfile . '.jpg');
        imagejpeg($imagecreatefrompng, $poster);

        //昵称位置
        imagefttext($imagecreatefrompng, 24, 0, 119, 40, $imagecolorallocate_nickname, $ttf_msyh, $wechatUser->getNickname());

        //商品图
        if ($productInfo->orderImage) {
            $paths = pathinfo($productInfo->orderImage);
            $ext = $paths['extension'];
            $productImg = File::downloadFromUrl($productInfo->orderImage, 'product-' . $newfile . '.' . $ext);
            Image::make($productImg)->resize(530, 530)->save($productImg);
            $forderImg = File::imagecreateByExt($productImg, $ext);
            imagecopy($imagecreatefrompng, $forderImg, 25, 130, 100, 100, imagesx($forderImg), imagesy($forderImg));
            @unlink($productImg);
        }

        //商品说明
        imagefttext($imagecreatefrompng, 36, 0, 25, 700, $imagecolorallocate_nickname, $ttf_msyh, $productInfo->title);
        imagefttext($imagecreatefrompng, 26, 0, 25, 760, $imagecolorallocate_nickname, $ttf_msyh, $productInfo->productDesc);

        //小程序码 agentid=1&city_id=1
        $scene = 'agentid=' . $this->user->getUserId() . '&city_id=' . $city_id . '&product_id=' . $productInfo->id;
        $miniQr = WechatService::createMiniQr('qr-' . $newfile . '.jpg', $scene, 'pages/product/product');
        Image::make($miniQr)->resize(136, 136)->save($miniQr);
        $fminiQr = imagecreatefromjpeg($miniQr);
        imagecopy($imagecreatefrompng, $fminiQr, 414, 680, 0, 0, imagesx($fminiQr), imagesy($fminiQr));
        imagejpeg($imagecreatefrompng, $poster);

        $url = Upload::uploadOss($poster);

        @unlink($miniQr);
        @unlink($poster);

        if (empty($url)) {
            Log::error('上传商品分销海报失败');
            throw new \Exception('上传商品分销海报失败');
        }

        $distributorPosterEntity = DistributorPosterEntity::findByUserId($this->user->getUserId());
        if (empty($distributorPosterEntity)) {
            $distributorPosterEntity = DistributorPosterEntity::getNewInstance();
        }
        $distributorPosterEntity->setCreatedAt(Carbon::now()->toDateTimeString());
        $distributorPosterEntity->setOpenid($wechatUser->getOpenid());
        $distributorPosterEntity->setUserId($this->user->getUserId());
        $distributorPosterEntity->setUrl($url);
        $distributorPosterEntity->setType(Constant::POSTER_TYPE_DEFAULT);
        $distributorPosterEntity->setProductId($productInfo->id);
        $distributorPosterEntity->save();
        Log::info('商品分销海报生成成功 url:' . $url);
    }

    public function makeConvertible(): void
    {

    }

    /**
     * 新文件名
     * @param string $name
     * @param string $type
     * @param int $id
     * @return string
     */
    public function getFilename(string $name, string $type = 'default', int $id = 0): string
    {
        switch ($type) {
            case self::FILENAME_POSTER:
                // todo
                break;
            case self::FILENAME_POSTER_PRODUCT:
                $name .= '-product-' . $id;
                break;
            default:
                break;
        }
        return $name;
    }
}
